#include "preHeader.h"
#include "Session/GameSession.h"
#include "Session/GameSessionHandler.h"
#include "SQLHelper.h"

int GameSessionHandler::HandleLoadAllInstCfgData(GameSession *pSession, INetPacket &pck, const RPCActor::RequestMetaInfo &info)
{
	auto LoadAllInstCfgData = [GSRPCAsyncTaskArgs]() {
		TNetBuffer<65536> buffer;
		auto connPtr = sMysqlDatabasePool.GetCharDB()->GetConnAutoPtr();
		if (connPtr) {
			auto rst = connPtr->QueryFormat(
				"SELECT * FROM `%s`", GetTableName<inst_configure>());
			if (rst) {
				while (rst.NextRow()) {
					auto row = rst.Fetch();
					auto instInfo = LoadEntityFromMysqlRow<inst_configure>(row);
					SaveToINetStream(instInfo, buffer);
				}
				GameSession::Feedback(gsPtr, buffer, info.sn);
			} else {
				GameSession::FeedbackError(gsPtr, info.sn, DBPErrorDeleteMysqlFailed);
			}
		} else {
			GameSession::FeedbackError(gsPtr, info.sn, DBPErrorConnectMysqlFailed);
		}
	};
	sDeferAsyncTaskMgr.AddTask(CreateAsyncTask(LoadAllInstCfgData));
	return SessionHandleCapture;
}

int GameSessionHandler::HandleSaveInstCfgData(GameSession *pSession, INetPacket &pck)
{
	auto SaveInstCfgData = [GSAsyncTaskArgs]() {
		uint32 cfgID;
		std::string_view cfgValue;
		(*pckPtr) >> cfgID >> cfgValue;
		auto connPtr = sMysqlDatabasePool.GetCharDB()->GetConnAutoPtr();
		if (connPtr) {
			auto rst = connPtr->QueryFormat(
				"UPDATE `%s` SET `cfgValue`='%s' WHERE `cfgID`=%u",
				GetTableName<inst_configure>(),
				SQL_ESCAPE_STRING(cfgValue).c_str(), cfgID);
			if (rst) {
				WLOG("Update cfgID[%u] failed.", cfgID);
			}
		}
	};
	sAsyncTaskMgr.AddTask(CreateAsyncTask(SaveInstCfgData));
	return SessionHandleCapture;
}
